import Vue from "vue";
import VueI18n from "vue-i18n";

import { getLanguage } from "@/utils/cookies";

// element-ui built-in lang
import iviewEnLocale from "view-design/dist/locale/en-US";
import iviewZhLocale from "view-design/dist/locale/zh-CN";
import iviewJaLocale from "view-design/dist/locale/ja-JP";
import iviewKoLocale from "view-design/dist/locale/ko-KR";

// User defined lang
import enLocale from "./en";
import zhLocale from "./zh";
import jaLocale from "./ja";
import koLocale from "./ko";

Vue.use(VueI18n);

const messages = {
  en: {
    ...enLocale,
    ...iviewEnLocale
  },
  zh: {
    ...zhLocale,
    ...iviewZhLocale
  },
  ja: {
    ...jaLocale,
    ...iviewJaLocale
  },
  ko: {
    ...koLocale,
    ...iviewKoLocale
  },
};

export const getLocale = () => {
  const cookieLanguage = getLanguage();
  if (cookieLanguage) {
    document.documentElement.lang = cookieLanguage;
    return cookieLanguage;
  }

  const language = navigator.language.toLowerCase();
  const locales = Object.keys(messages);
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      document.documentElement.lang = locale;
      return locale;
    }
  }

  // 默认语言是中文
  return "zh";
};

const i18n = new VueI18n({
  locale: getLocale(),
  messages
});

export default i18n;
